<div class="container" style="margin-top:10px;">
	<div class="row">
<style>

::-webkit-scrollbar {
    width: 8px;
}
 
::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 8px rgba(200,200,200,0.3); 
}
 
::-webkit-scrollbar-thumb {
    -webkit-box-shadow: inset 0 0 8px #999; /*rgba(60,60,60,0.5)*/
}

#header-breadcrumb{display: none;}
.footer-bottom{padding:2px;font-size:80%;}
#maincontent {margin:0;padding:0;}

#left-sidebar .ui-portlet{margin:0px;}
#left-side-affix{box-shadow:0 0 3px rgba(0, 0, 0, 0.15);}
#left-sidebar .btn-group .btn{padding:4px 16px;}

#insert-style-list ul,ul.editor-painter-list{padding:10px;margin:0;}
#insert-style-list li,.editor-painter-list li{
	cursor: pointer;padding:5px 0px;border-top:1px solid #f9f9f9;list-style:none;
}
#insert-style-list li img,.editor-painter-list li img{max-width: 100%;}

#insert-style-list li:hover,.editor-painter-list li:hover{	background-color:#efefef;}
.mix{display: none;}

.cke_reset_all, .cke_reset_all *{
	position: initial;
}
.affix{top:0px;background-color:#FFF;z-index:100;position: fixed;}
.col-xs-6 {width: 49%;}
.color-swatch{width:28px;height:28px;border-radius: 14px;cursor: pointer;float: left;margin:4px 2px;
	box-shadow: 1px 1px 3px #5b616d inset, 2px 2px 4px #fff;
}
.color-box {width:16px;height:16px;cursor: pointer;border:solid 1px #ddd;margin-top:3px;float: left;margin-right:5px;}
.color-swatch:hover,.color-swatch.active {	
-webkit-transform:scale(1.1);-moz-transform:scale(1.1);-ms-transform:scale(1.1);
-o-transform:scale(1.1);transform:scale(1.1);
-webkit-box-shadow:inset 1px 1px 3px #5b616d,0 0 10px #45bcda;
-moz-box-shadow:inset 1px 1px 3px #5b616d,0 0 10px #45bcda;
box-shadow:inset 1px 1px 3px #5b616d,0 0 10px #45bcda;
}
.col-sm-4,.col-sm-6,.col-sm-2{padding-right: 5px;padding-left: 5px;}
#params-setting ul{padding:0;}
#params-setting .title{font-size:16px;font-weight:bold;padding-bottom:3px;margin-bottom:5px;margin-top:15px;border-bottom:1px solid #DDD;}
#params-setting li{list-style:none;}
#params-setting label{display:block;line-height:18px;font-weight:normal;}
#params-setting input{margin-right:5px;margin-top:3px;float:left;}
.cke_button__source_label{display:none;}
.cke_combo__font .cke_combo_text{padding-left:5px;width:60px;}
.cke_combo__styles .cke_combo_text{width:80px;}
.cke_chrome {border: none;box-shadow: 0 0 1px 1px rgba(172,181,194,0.56);}
#editor-styles .nav > li > a{padding:10px 5px;text-align:center;}

#editor-tpls-list .style-list .content, #template-modal-body .style-list .content{cursor: pointer;margin-top:20px;padding: 0 5px;overflow-x:hidden;overflow-y:hidden;box-shadow: 0 0 3px rgb(170, 170, 170);}
#editor-tpls-list .style-list .tools,#template-modal-body .style-list .tools{display:none;}
#editor-tpls-list .row{margin:0 -5px;}
#editor-tpls-list .col-md-6{padding:0 5px;}
</style>
<!--[if lt IE 9]>
	alert("温馨提醒：请使用谷歌浏览器已获得最佳体验。");
<![endif]-->
	<div id="left-sidebar" class="col-sm-3 hidden-xs hidden-print">
		<div id="left-side-affix" > <!-- data-spy="affix" data-offset-top="110" -->
		<button type="button" id="btn-help" class="btn btn-default pull-right" data-container="body" data-toggle="popover" data-placement="bottom" 
		data-content="提示：点击内容块将自动插入相应内容到编辑器,修改成自己需要的文字即可。">?</button>
		<ul class="nav nav-tabs" role="tablist">		  
		  <li class="active"><a href="#editor-styles" role="tab" data-toggle="tab">样式</a></li>
		  <li id="tab-tpl-trigger"><a href="#editor-tpls" role="tab" data-toggle="tab">模板</a></li>
		</ul>

		<!-- Tab panes -->
		<div class="tab-content">
		  <div class="tab-pane active" id="editor-styles"  style="padding:0px 0px;position:relative;">
		  		<div>
			    	<ul class="nav nav-pills nav-stacked" style="width:72px;position:absolute;left:-72px;background:rgba(182, 182, 182, 0.3);">
					  <li class="active ">
					    <a href="#editor-template" class="filter"  data-filter="all" role="tab" data-toggle="tab"> 全部</a>
					  </li>
					  <portlet portlet="body" list_tpl="inner" limit="50" model="Tag" recursive="-1" order="priority asc" info="conditions[cate_id]=214">
							<li>
							    <a class="filter" data-filter=".tagtpl-{{$item['id']}}" href="#editor-template" role="tab" data-toggle="tab" href="javascript:void(0)"> {{$item['name']}} </a>
							</li>
					  </portlet>
					<li><a href="#image-list" role="tab" data-toggle="tab"><i class="fa fa-image"></i>图片素材</a></li>
					  <li><a href="#fovor-style-list" role="tab" data-toggle="tab"><i class="fa fa-heart-o"></i>收藏</a></li>
					</ul>
				</div>		  		
		  		<div id="insert-style-list" class="tab-content" style="padding:px;height:500px;overflow-y:auto;overflow-x:hidden;">
		  			
					<div id="editor-template" class="tab-pane active">
				  		<portlet ulclass="editor-template-list row" portlet="notitle" list_tpl="inner" limit="200" model="EditorStyle" order="sort desc" info="recursive=1&fields[0]=content&fields[1]=name&fields[2]=summary&fields[3]=id&conditions[cate_id]=1&conditions[recommend]=1&order=sort desc">
								<li class="col-xs-12 mix {{loop $item_all['Tag'] $tag}} tagtpl-{{$tag['id']}}{{/loop}}" data-id="{{$item['id']}}" title="点击插入此内容">{{$item['content']}}</li>
						</portlet>
					</div>
					<div id="image-list" class="tab-pane">
						<portlet ulclass="editor-template-list row" portlet="notitle" list_tpl="inner" limit="100" model="EditorStyle" order="sort desc" 
						info="recursive=1&fields[]=name&fields[]=summary&fields[]=coverimg&conditions[cate_id]=4&conditions[recommend]=1&fields[]=id&order=sort desc">
							<li class="col-xs-12 mix {{loop $item_all['Tag'] $tag}} tagtpl-{{$tag['id']}}{{/loop}}" data-id="{{$item['id']}}"  title="点击插入此内容">
								<img src="{{$item['coverimg']}}">
							</li>
						</portlet>
					</div>
					<div id="fovor-style-list" class="tab-pane">
					{{if $current_user_id}}
			  			<portlet ulclass="row" cache="no" portlet="notitle" list_tpl="inner" limit="100"
						 model="EditorStyle" order="EditorStyle.sort desc" 
						 info="recursive=1&joins[0][table]=favorites&joins[0][alias]=Favorite&joins[0][type]=inner&joins[0][conditions][Favorite.model]=EditorStyle&joins[0][conditions][]=Favorite.data_id=EditorStyle.id&conditions[]=Favorite.creator_id=$current_user_id&fields[]=cate_id&fields[]=content&fields[]=name&fields[]=id&fields[]=coverimg">
								{{if $item['cate_id'] == 4}}
								<li class="col-xs-12" data-id="{{$item['id']}}"  title="点击插入此内容"><img class="135editor" src="{{$item['coverimg']}}"></li>
								{{else}}
								<li class="col-xs-12" data-id="{{$item['id']}}"  title="点击插入此内容">{{$item['content']}}</li>
								{{/if}}
						</portlet>
					{{else}}
						<div style="padding:10px">
							<p>登录后可以在<a href="{{$this->Html->url('/style-center?cate_id=1')}}" target="_blank">样式中心</a>收藏样式与模板。</p>
							<p><a href="{{$this->Html->url('/users/login')}}?referer=/style-center?cate_id=1" target="_blank">立即登录</a></p>
						</div>
					{{/if}}
					</div>					
				</div>
		  </div>
		  
		  <div class="tab-pane" id="editor-tpls" style="padding:0px 0px;position:relative;">
		    	<ul id="editor-tpls-navtab" class="nav nav-pills nav-stacked" style="width:72px;position:absolute;left:-72px;background:rgba(182, 182, 182, 0.3);">
				  
				  {{if $CurrentUser['id']}}
				  <li id="personal-tpl-list-li"><a href="#personal-tpl-list-1" role="tab" data-toggle="tab">个人原创</a></li>
				  <li id="favorite-tpl-list-li"><a href="#favorite-tpl-list-1" role="tab" data-toggle="tab"><i class="glyphicon glyphicon-heart"></i>收藏</a></li>
				  {{/if}}
				  <li>
				    <a href="#recommend-tpl-list-1" role="tab" data-toggle="tab">系统推荐</a>
				  </li>
				  
				</ul>
				<button type="button" class="btn btn-warning btn-xs" style="display:block; width: 100%;" onclick="openTplModal();">
				  弹窗选择模板
				</button>
				<div class="tab-content"  style="padding:0 10px;height:500px;overflow-y:auto;overflow-x:hidden;" id="editor-tpls-list"></div>					
		  </div>
	  
		</div>
			
		</div>
	</div>
	<div class="col-sm-6">
	<form action="" class="form-horizontal" role="form" target="_blank" id="WxMsgViewForm" method="post" accept-charset="utf-8">
		<div class="form-group" id="divWxMsgContent">
			<div class="col-sm-12 controls">
				<input type="hidden" name="template_id" id="template_id" />
				<input type="hidden" name="template_name"  id="template_name"/>
				<input type="hidden" name="msg_id" />
				<textarea name="content" class="form-control" rows="3" cols="30" id="WxMsgContent"></textarea>
				
				<!-- <input type="button" class="btn btn-primary" id="save-as-msg" value="存为文章">		-->
				<input type="button" class="btn btn-primary" id="copy-editor-html" value="复制内容">	
				<input type="button" class="btn btn-warning" id="save-as-template" value="存为模板">
				<input type="button" class="btn btn-danger" id="clear-editor" value="清空内容">
							
				<input type="button" class="btn btn-primary" id="html-to-image" value="长微博图文">
			</div>
		</div>
		<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
		  <div class="modal-dialog">
		    <div class="modal-content">
		      <div class="modal-header">
		        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">{{__('Close')}}</span></button>
		        <h4 class="modal-title">保存模板</h4>
		      </div>
		      <div class="modal-body">
		        <p><input type="text" placeholder="请输入模板名称后点击保存" name="template_name" id="dialog-template-name" class="form-control"></p>
		        <p><label><input type="checkbox" name="push_tpl_center" value="1">发布到模板中心(不勾选时存为私人模板)</label> <a href="/audit-rules.html" target="_blank">审核规则</a> </p>
		        <p><label id="auto_cover_tpl" class="hidden"><input type="checkbox" name="auto_cover_tpl" checked="checked" value="1">覆盖原有模板</label></p>
		      </div>
		      <div class="modal-footer">
		        <button type="button" class="btn btn-default" data-dismiss="modal">{{__('Close')}}</button>
		        <button type="button" id="dialog-save-template" class="btn btn-primary">{{__('Save')}}</button>
		      </div>
		    </div><!-- /.modal-content -->
		  </div><!-- /.modal-dialog -->
		</div><!-- /.modal -->
	</form>
	</div>
	<div class="col-sm-2" >
		<div id="params-setting"> <!-- data-spy="affix" data-offset-top="110" -->
			<small>
				<ul>
				<li class="title">格式设置</li>
					<li><button class="btn btn-default btn-xs popover-trigger" data-container="body" data-toggle="popover"  data-placement="top" 
					data-content="首行缩进只对段落有效" id="p-text-indent"> 首行缩进</button> 
					 
					 <button class="btn btn-default btn-xs" id="p-text-indent-remove"> 取消缩进</button>
					 <button class="btn btn-default btn-xs" id="p-remove-empty"> 删除空行</button>
					 
					 </li>
				
				<li class="title">颜色操作</li>
					
					<li><label><input type="checkbox" checked="checked" id="replace-color-all" value="1"> 全文换色</label></li>
					<li>
						<label><input type="checkbox" id="paste-current-color" value="1"> 粘贴自动换色</label>
					</li>
					<li><button class="btn btn-default btn-xs popover-trigger" data-container="body" 
					data-toggle="popover"  data-placement="top" 
					data-content="随机轮换色为每隔一项内容自动切换一种的颜色，仅对135编辑器的样式有效。"
					   id="135-random-color"> 
					
					随机轮换色
					
					</button> &nbsp;
					</li>
				<!-- <li><label><div class="color-box" id="gradient-light-color"> </div> 渐变背景的浅色</label></li>
				<li><label><div class="color-box" id="text-foreground-color" style="background-color:#FFF;"> </div> 带背景色的文本颜色</label></li>
				 -->
				<li class="title">样式处理 <i class="glyphicon glyphicon-question-sign popover-trigger" data-container="body" data-toggle="popover"  data-placement="left"  title="图片处理提示" 
				data-content="提示图片边框后，再点击图片圆形，图片会变成圆形且带圆形边框。再次点击图片边框后，又会变成方形带边框。
				圆角、边框与阴影的效果为自动处理，如果对效果不满意可以同时按“ctrl+z”进行撤消"></i> </li>
					<li>
					<button class="btn btn-default btn-xs" id="set-image-radius"> 图片圆形  </button>
					 <button class="btn btn-default btn-xs" id="set-image-border"> 图片边框 </button>
					 
					 <br/>
						<button class="btn btn-default btn-xs" id="flat-strip-radius"> 去圆角</button>
						<button class="btn btn-default btn-xs" id="flat-add-radius"> 加圆角</button>
						<button class="btn btn-default btn-xs" id="flat-strip-border"> 去边框</button>
						<!--  <button class="btn btn-default btn-xs" id="flat-add-border"> 加边框</button>  -->
						<button class="btn btn-default btn-xs" id="flat-strip-shadow"> 去阴影 </button>
						<button class="btn btn-default btn-xs" id="flat-add-shadow"> 加阴影 </button>						
					</li>
				<!-- <label><input type="checkbox" id="p_text_indent" value="1"> 段落首行缩进</label> -->
				</ul>
			</small>
		</div>
	</div>
	<div style="clear:both;"></div>
  </div>



<section style="width:140px;position:fixed;top:76px;right:-5px;height:320px;">
	<div class="panel panel-primary">
	  <div class="panel-heading"><h3 class="panel-title">配色方案</h3></div>
	  <div class="panel-body" style="padding:0;">
	    <ul class="clearfix" style="list-style:none;padding:0 5px">
            <li class="color-swatch" style="background-color: #c3272b"></li>
            <li class="color-swatch" style="background-color: #f20c00;"></li>
            <li class="color-swatch" style="background-color: #ff461f;"></li>
            <li class="color-swatch" style="background-color: #f96e57;"></li>
            
            <li class="color-swatch" style="background-color: #c93756;"></li>
            <li class="color-swatch" style="background-color: #f47983;"></li>
            <li class="color-swatch" style="background-color: rgb(255, 175, 205);"></li>
            <li class="color-swatch" style="background-color: #ffb3a7;"></li>
            
            
            <!-- 青碧 -->
             <li class="color-swatch" style="clear:left;background-color: #48c0a3;"></li>
            <li class="color-swatch" style="background-color: #1bd1a5;"></li>
            <li class="color-swatch" style="background-color: #7bcfa6;"></li>
            <li class="color-swatch" style="background-color: rgb(141, 225, 163);"></li>
            
           
            
            <!-- 黄色 -->
            <li class="color-swatch" style="clear:left;background-color: rgb(255, 129, 36);"></li>
            <li class="color-swatch" style="background-color:#ffa631;"></li>
            <li class="color-swatch" style="background-color: rgb(255, 202, 0);"></li>
            
            
            <!-- 绿色 -->
            
             <li class="color-swatch" style="clear:left;background-color:#0eb83a;"></li>
            <li class="color-swatch" style="background-color:#00e500;"></li>
            <li class="color-swatch" title="草绿" style="background-color: #40de5a;"></li>
            
            <li class="color-swatch" title="绿沈" style="clear:left;background-color: #0c8918;"></li>            
            <li class="color-swatch" style="background-color: #0aa344;"></li>
            
            <li class="color-swatch" style="background-color: #21a675;"></li>
            
            
            
            <li class="color-swatch" style="clear:left;background-color: rgb(142, 201, 101);"></li>
            <li class="color-swatch" style="background-color: #96ce54;"></li>
            <li class="color-swatch" style="background-color: #9ed900;"></li>
            <li class="color-swatch" style="background-color: #bddd22;"></li>
            
            <!-- 蓝色 -->
            <li class="color-swatch" style="clear:left;background-color: #003472;"></li>
            <li class="color-swatch" style="background-color:#4b5cc4;"></li>
            <li class="color-swatch" style="background-color: rgb(95, 156, 239);"></li>
            <li class="color-swatch" style="background-color:#44cef6;"></li>
            <!-- 紫色 -->
            <li class="color-swatch" style="clear:left;background-color:#8d4bbb;"></li>
            <li class="color-swatch" style="background-color: rgb(166, 91, 203);"></li>
            <li class="color-swatch" style="background-color:#cca4e3;"></li>

            <li class="color-swatch" style="background-color: rgb(190, 119, 99);"></li>
            
            
			<!-- 黑灰色 -->
            <li class="color-swatch" data-color="#efefef" style="clear:left;background-color: rgb(0, 1, 2);"></li>
            
            <li class="color-swatch" style="background-color: #818081;"></li>
            <li class="color-swatch" style="background-color: rgb(162, 161, 160);"></li>
            <li class="color-swatch" style="background-color: #bacac6;"></li>
            
        </ul>
        <hr style="margin:2px;"/>
        <ul class="clearfix" style="list-style:none;padding:0 5px" title="浅色颜色不支持全文调色，选选择要调色的部分内容或者全选内容">
        	<li class="color-swatch" data-change="select" data-color="#666" style="background-color: rgb(216, 215, 200);"></li>
        	<li class="color-swatch" data-change="select" data-color="#666" style="background-color: rgb(219, 238, 243);"></li>
        	<li class="color-swatch" data-change="select" data-color="#666" style="background-color: #faebff"></li>


        	<li class="color-swatch" data-change="select" data-color="#666" style="background-color: #fcf8e3"></li>
        	<li class="color-swatch" data-change="select" data-color="#666" style="background-color: #dff0d8"></li>
        	<li class="color-swatch" data-change="select" data-color="#666" style="background-color: #f2dede"></li>
			
			<li class="color-swatch" data-change="select" style="background-color:#eedeb0"></li>
			<li class="color-swatch" data-change="select" style="background-color:#f0fcff"></li>
			
			<li class="color-swatch" data-change="select" style="background-color:#f0f0f4"></li>
        </ul>
	  </div>
	</div>        
</section>


{{$this->Html->script(array(
	'ckeditor/ckeditor.js',
))}}



<script>
	

	
$(function(){
	$('#btn-help').popover();
	$('#editor-type-pop').popover({
	  trigger: 'hover'
	});
});

var unstrip_space_line_style = true; // 保留空行粘贴内容的样式，为false时空行粘贴纯文本


function strip_stack_span(html){ // 将层叠的上下级span标签合并，同时合并两者的style属性
	var docObj = $('<div>'+html+'</div>');
	var has_secspan = false;
	do
	{
		has_secspan = false;
		docObj.find('span:has(span)').each(function(i){
    		var innerobj = $(this).find('span');
    		if($.trim($(this).text()) == $.trim(innerobj.text())) {

    			has_secspan = true;
    			var style= $(this).attr('style');
    			var innserstyle = innerobj.attr('style');
    			$(this).attr('style',style +";"+innserstyle).html($(this).text());
    		}
    	});
	}while(has_secspan && docObj.find('span:has(span)').size() > 0);
	return docObj.html();
}

function strip_tags(html){
	var pasteObj = $(html);
	//pasteObj.find('br').removeAttr('style').removeAttr('class');
	if(pasteObj.find('*').size() > 1){
		pasteObj.find('br,div,p').after("===BR===");  //纯文本，仅保留换行
	}
	
	var text = pasteObj.text();
	text = text.replace(/\=\=\=BR\=\=\=/g, "<br>");
	return text;
}

$(function(){
	$('#left-side-affix').width($('#left-sidebar').width());
	
	ckeditors['WxMsgContent'] = CKEDITOR.replace( 'WxMsgContent',
		    {
		        customConfig : '{{$this->Html->script("/js/ckeditor/front-config.js",array('onlyurl'=>true))}}',
		        toolbar : 'ANONY',
		        height:450
		        //,format_p : { element: 'p', attributes: {'class':'pp','style': 'text-indent:2em', }}
		    });
	
	//config.line_height="1em;1.1em;1.2em;1.3em;1.4em;1.5em";
	//CKEDITOR.config.removeFormatTags = 'b,div,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var,form,input,textarea';

	
    
	//CKEDITOR.config.format_p = { element: 'p',attributes: {'class':'pp','style': 'text-indent:2em', },styles :{'text-indent':'2em'}};
	
	window.onbeforeunload = function(event){   
		if(ckeditors['WxMsgContent'].getData() != ""){
			if( window.localStorage){
				localStorage._135content = ckeditors['WxMsgContent'].getData();
			}
			event.returnValue = "即将离开页面，是否确认编辑的内容已使用并废弃？";   
		}   
	}
	
	CKEDITOR.on( 'instanceReady', function( e ){
		/*e.editor.document.appendStyleSheet( '{{$this->Html->url("/stylevars/getcss.css")}}' );
		e.editor.document.appendStyleSheet( '{{$this->Html->url("/css/ui-customer.css")}}' );
		//e.editor.setMode( 'source' );
		e.editor.on( 'mode', function( e ){
			if(e.editor.mode == 'wysiwyg'){
				e.editor.document.appendStyleSheet( '{{$this->Html->url("/stylevars/getcss.css")}}' );
				e.editor.document.appendStyleSheet( '{{$this->Html->url("/css/ui-customer.css")}}' );
			}
		});*/
		//$('.cke_top').width($('.cke_top').width());
		//$('.cke_top').addClass('clearfix').affix({offset:{top: 110}});
		
		if( window.localStorage){ // 本地临时存储编辑器内容
			if(typeof localStorage.content != "undefined"){
				e.editor.setData(localStorage._135content);
			}
			setInterval(function(){
				localStorage._135content = e.editor.getData();
			},10000);			
		}

		e.editor.focus();
	
		/*e.editor.dataProcessor.htmlFilter.addRules({
		    elements :{
		        p : function( element ){ //CKEDITOR.htmlParser.element
		        	if(element.attributes.style){
		        		element.attributes.style += 'text-indent:2em';
		        	}
		        	else{
		        		element.attributes.style = 'text-indent:2em';
		        	}		        	
		            element.addClass('thiny_p');
		        }
		    }
		});*/
				
		
		bindEditorEvent(e.editor);		
	});
	
	function bindEditorEvent(editor){
		editor.document.on( 'click', function( evt ) {
			var element;
			if(evt.data.element){
				element = evt.data.element;
			}
			else{
				element = evt.data.getTarget()
			}
			
		    if ( element.getHtml() == element.getAttribute( 'placeholder' ) ){
		    	if( element.is( 'blockquote' )) {
		    		element.setHtml("&nbsp;");
		    	}
		    	else{
		    		element.setHtml("&nbsp;");
		    	}
		    }
		} );
		
	};
	
	ckeditors['WxMsgContent'].on('key',function(event) {
		// Do not capture CTRL hotkeys.
		var keyCode = event.data.keyCode;
		
		if ( event.data.ctrlKey || event.data.metaKey )
			return;
		if(keyCode == 13){
			//var element = ckeditors['WxMsgContent'].getSelection().getStartElement();
			// 段落自动换行
			//if(element.getName() == 'p'){
			//	$(element.$).css('text-indent','2em');
			//};
		}
	});
	
	/*ckeditors['WxMsgContent'].on('click', function( evt ) {
		var element;
		if(evt.data.element){
			element = evt.data.element;
		}
		else{
			element = evt.data.getTarget()
		}
		
	    if ( element.getHtml() == element.getAttribute( 'placeholder' ) ){
	    	if( element.is( 'blockquote' )) {
	    		element.setHtml("&nbsp;");
	    	}
	    	else{
	    		element.setHtml("&nbsp;");
	    	}
	    }
	});
	
	ckeditors['WxMsgContent'].on( 'doubleclick', function( evt ) {
	    var element = evt.data.element;
	    if ( element.getHtml() == element.getAttribute( 'placeholder' ) ){
	    	if( element.is( 'blockquote' )) {
	    		element.setHtml("&nbsp;");
	    	}
	    	else{
	    		element.setHtml("&nbsp;");
	    	}
	    }
	} );*/
	

	ckeditors['WxMsgContent'].on('paste', function( evt ) {
    // Update the text
    	evt.data.dataValue = strip_stack_span(evt.data.dataValue);
    	// alert(evt.data.dataValue);
    	var pasteHtml = '<div>'+evt.data.dataValue+'</div>';
    	var pasteObj = $(pasteHtml);
    	
    	var element = evt.editor.getSelection().getStartElement();
		var nodeName = element.getName();
    	
		if(pasteObj.find('img').size()>0){
			
			if(current_select_bgcolor && $('#paste-current-color')[0].checked ){
				evt.data.dataValue = parseHtml( evt.data.dataValue ,current_select_bgcolor,'#FFF' )
			}
			return ; //有图片时不处理
		}
		//h2,h3,h4,h5,h6
		else if(pasteObj.find('div,section,video,iframe,blockquote').size() > 0){
    		if(pasteObj.find('[style]').size()>0) {
    			if(current_select_bgcolor && $('#paste-current-color')[0].checked ){
    				evt.data.dataValue = parseHtml( evt.data.dataValue ,current_select_bgcolor,'#FFF' )
    			}
    			return ; //含有块级元素，且包含style属性时，不处理
    		}
    	}
		
		if(nodeName=='blockquote' || nodeName=='pre' || nodeName=='section'){ //粘贴到已有的blockquote，pre，section时，使用纯文本
			var text = strip_tags(pasteHtml);
			evt.data.dataValue = text;
			return;
		}
		
		if(unstrip_space_line_style && $.trim(element.getText()) == ""){
			if(current_select_bgcolor && $('#paste-current-color')[0].checked ){
				evt.data.dataValue = parseHtml( evt.data.dataValue ,current_select_bgcolor,'#FFF' )
			}
			return; //对于空的元素，保留原文的格式
		}
		
		// var selectedText = evt.editor.getSelection().getSelectedText();
		
		// 其他的对内容的style进行过滤，替换成当前的样式
		
		//if(element.getName() =='p' || element.getName() =='div' || element.getName() =='span')
		{
			var cssText = element.getAttribute('style');
			var text = strip_tags(pasteHtml);
			
			if(cssText==null || cssText==""){
				evt.data.dataValue = '<'+nodeName+'>'+ text +'</'+nodeName+'>';
			}
			else{
				evt.data.dataValue = '<'+nodeName+' style="'+cssText+'">'+ text +'</'+nodeName+'>';
			}
		}

	}, ckeditors['WxMsgContent'].element.$);


	ckeditors['WxMsgContent'].focus();


	$('#p-text-indent').click(function(){		
		var range = ckeditors['WxMsgContent'].getSelection().getRanges()[ 0 ],
	    el = ckeditors['WxMsgContent'].document.createElement( 'div' );	
		if(range){
			el.append( range.cloneContents() );
			var html = el.getHtml();
			if(html != ""){
				var obj = $('<div id="editor-content">'+html+"</div>");
				obj.find('p').css('text-indent','2em');
				
				range.deleteContents();
				var newHtml = obj.html();
				ckeditors['WxMsgContent'].insertHtml(newHtml);
				html = null; newHtml = null; obj = null;
				return;
			}
		}
		var element = ckeditors['WxMsgContent'].getSelection().getStartElement();
		$(element.$).css('text-indent','2em');
	});
	
	$('#p-remove-empty').click(function(){
		var html = getDealingHtml();	
		var obj = $('<div>'+html+'</div>');
		obj.find('p').each(function(){
			if($(this).html() == "<br>" || $(this).html() == "&nbsp;" ){
				$(this).remove();
			}
		});
		setDealingHtml(obj.html())
		obj = null;
	})
	$('#p-text-indent-remove').click(function(){
		var range = ckeditors['WxMsgContent'].getSelection().getRanges()[ 0 ],
	    el = ckeditors['WxMsgContent'].document.createElement( 'div' );
	
		if(range){
			el.append( range.cloneContents() );
			var html = el.getHtml();
			if(html != ""){
				var obj = $('<div id="editor-content">'+html+"</div>");
				obj.find('p').css('text-indent','');
				
				range.deleteContents();
				var newHtml = obj.html();
				ckeditors['WxMsgContent'].insertHtml(newHtml);
				html = null; newHtml = null; obj = null;
				return;
			}
		}
		var element = ckeditors['WxMsgContent'].getSelection().getStartElement();
		$(element.$).css('text-indent','');
	})
	
	$('#flat-strip-shadow').click(function(){
		var html = ckeditors['WxMsgContent'].getData();
		var obj = $('<div>'+html+'</div>');
		obj.find('*').css('box-shadow','');
		var newHtml = obj.html();
		ckeditors['WxMsgContent'].setData(newHtml);
	});
	
	$('#flat-add-shadow').click(function(){
		var html = ckeditors['WxMsgContent'].getData();
		var obj = $('<div>'+html+'</div>');
		
		obj.find('*').each(function(){			
					if( $(this).css('background-color') == 'transparent' ||  $(this).css('background-color') == '' ){
					}
					else{
						$(this).css('box-shadow','rgba(205, 205, 205,0.9) 3px 3px 2px');
					}
		});
		var newHtml = obj.html();
		ckeditors['WxMsgContent'].setData(newHtml);
	});	
	
	
	$('#set-image-radius').click(function(){
		var html = getDealingHtml();	
		var obj = $('<div>'+html+'</div>');
		obj.find('img').css('border-radius','50%');
		setDealingHtml(obj.html())
		obj = null;
	});
	$('#set-image-border').click(function(){
		var html = getDealingHtml();	
		var obj = $('<div>'+html+'</div>');
		obj.find('img').css({"background-color":"#fff","border-radius":"4px","max-width":"100%","padding":"4px","border":"1px solid #ddd"});
		setDealingHtml(obj.html())
		obj = null;
	})
	
	$('#flat-add-radius').click(function(){
		var html = getDealingHtml();	
		var obj = $('<div>'+html+'</div>');
		obj.find('*').each(function(){
			if( $(this).css('background-color') != 'transparent' &&  $(this).css('background-color') != '' ){
				$(this).css('border-radius','4px');
			}			
		});
		setDealingHtml(obj.html())
		obj = null;
	});
	
	$('#flat-strip-radius').click(function(){
		var html = getDealingHtml();	
		var obj = $('<div>'+html+'</div>');
		obj.find('*').css('border-radius','');
		setDealingHtml(obj.html())
		obj = null;
	});
	
	$('#flat-add-border').click(function(){
		var html = getDealingHtml();	
		var obj = $('<div>'+html+'</div>');
		obj.find('*').each(function(){
			if( $(this).css('background-color') != 'transparent' &&  $(this).css('background-color') != '' ){
				$(this).css('border','1px solid #efefef');
			}			
		});
		//obj.find('.135editor').css('border','1px solid #efefef');
		setDealingHtml(obj.html())
		obj = null;
	});
	$('#flat-strip-border').click(function(){
		var html = getDealingHtml();	
		var obj = $('<div>'+html+'</div>');
		
		obj.find('*').each(function(){
			//if( $(this).css('background-color') == 'transparent' ||  $(this).css('background-color') == ''  ){
			//}
			//else{
				$(this).css('border','');
				$(this).css('border-width','0');
			//}
		});
		
		setDealingHtml(obj.html())
		obj = null;
	})

	$(document).on('click','#insert-style-list li',function(){
		//data-135editor=\"true\"
		//多插入一个空行，防止有时无法选择到底部了，或者两个元素中间不方便插入内容。
		if($(this).find('.135editor').size()){
			insertHtml("<p>&nbsp;</p>" + $(this).html() + "<p>&nbsp;</p>"); 
		}
		else{ //最外围包装135editor容器
			insertHtml("<p>&nbsp;</p><section class=\"135editor\">" + $(this).html() + "</section><p>&nbsp;</p>"); 
		}		
	});

	$('.color-swatch').click(function(){
		$('.color-swatch').removeClass('active');
		$(this).addClass('active');
		var color = $(this).data('color'); //data-color为前景色，bgcolor为背景色，或者无背景文字的前景色
		var bgcolor = $(this).css('backgroundColor');
		var changeType = $(this).data('change');
		changeType = "all"; //关闭浅色必需选择区域才能换色的功能
		if(!color)  color = '#FFF';
		setBackgroundColor(bgcolor,color, changeType);
		//$('.editor-template-list li').each(function(){
		//	$(this).html( parseHtml($(this).html(),bgcolor,color) );
		//})
	});
	
	$('#135-random-color').click(function(){
		var html = getDealingHtml();	
		var obj = $('<div>'+html+'</div>');
		var bgcolors = ['#5BB75B','#2E8BCC','#F09609','#E51400','#7B4F9D','#E671B8','#008641','#20608E','#FFC40D'];
		
		var rd = Math.floor(Math.random() * ( bgcolors.length));
		var used = [];
		var current_bgcolor = bgcolors[rd];
		var components = obj.find('.135editor').each(function(i){
			if(i%random_color_step == 0){
				do
				{
					rd = Math.floor(Math.random() * ( bgcolors.length));
				}
				while(jQuery.inArray(rd,used) != -1);
				
				used[used.length] = rd;
				if( used.length == bgcolors.length ){
					used = [];
				}				
				
				current_bgcolor = bgcolors[rd];
			}
			$(this).html(parseHtml($(this).html(),current_bgcolor,current_select_color));
		});
		
		setDealingHtml(obj.html())
		obj = null;
	})
});
var random_color_step = 1;
var custom_style_set = false;
var current_select_bgcolor = null;
var current_select_color = '#FFF';


function getDealingHtml(){
	var range = ckeditors['WxMsgContent'].getSelection().getRanges()[ 0 ],
    el = ckeditors['WxMsgContent'].document.createElement( 'div' );
	if(range){
		el.append( range.cloneContents() );
		var html = el.getHtml();
		if(html != ""){
			return html;
		}
		else{
			return ckeditors['WxMsgContent'].getData();
		}
	}
	else{
		return ckeditors['WxMsgContent'].getData();
	}
}
function setDealingHtml(newHtml){
	var range = ckeditors['WxMsgContent'].getSelection().getRanges()[ 0 ],
    el = ckeditors['WxMsgContent'].document.createElement( 'div' );
	if(range){
		el.append( range.cloneContents() );
		var html = el.getHtml();
		if(html != ""){
			custom_style_set = true;
			range.deleteContents();
			ckeditors['WxMsgContent'].insertHtml(newHtml);
			html = null; newHtml = null;
			return;
		}
		else{
			return ckeditors['WxMsgContent'].setData(newHtml);
		}
	}
	else{
		return ckeditors['WxMsgContent'].setData(newHtml);
	}
}
function setBackgroundColor(bgcolor,color,changeType){

	current_select_bgcolor = bgcolor;
	current_select_color = color;
	var range = ckeditors['WxMsgContent'].getSelection().getRanges()[ 0 ],
	    el = ckeditors['WxMsgContent'].document.createElement( 'div' );
	
	if(range){
		el.append( range.cloneContents() );
		var html = el.getHtml();
		if(html != ""){
			custom_style_set = true;
			range.deleteContents();
			var newHtml = parseHtml(html,bgcolor,color);
			ckeditors['WxMsgContent'].insertHtml(newHtml);
			html = null; newHtml = null;
			return;
		}
		else{
			if( !$('#replace-color-all')[0].checked )
			{
				alert("没有选择要调色的内容，如要全文换色请在右侧勾选“全文换色”的选择框或者Ctrl+A全选内容再进行操作");
				//alert("没有选择要调色的内容，请选择内容后再进行调色。");
				return ;
			}
		}
	}

	if(changeType == 'select'){
		alert("浅色颜色不支持全文调色，请选择要调色的部分内容(可手动全选后调色)");
		return ;
	}
	else { //if(!custom_style_set || custom_style_set && confirm("进行过部分区域设色，是否放弃并全部重设")){
		
		if(custom_style_set) {
			alert("进行过部分区域换色，全文换色已不可用，如需要全部变色请全选内容后再进行操作");
			return false;
		}
		
		var html = ckeditors['WxMsgContent'].getData();	
		var newHtml = parseHtml(html,bgcolor,color);
		ckeditors['WxMsgContent'].setData(newHtml);
		html = null; newHtml = null;
		custom_style_set = false;
	}
	return;
}

function parseHtml(html,bgcolor,color){
	var obj = $('<div id="editor-content">'+html+"</div>");
	
	obj.find("*").each(function() {
		
		if(this.nodeName == "HR" || this.nodeName == "hr" ) {
			$(this).css('border-color',bgcolor);
			return ; // 水平线自动设置颜色
		}

		if(this.nodeName == ""  ) {
			return ; // 类型为空或者td时，不处理
		}
		
		if( $(this).data('bcless') ){
			
			var persent = $(this).data('bclessp') ? $(this).data('bclessp') : '10%';
			
			var bc_color;			
			if(isLightenColor(bgcolor) || $(this).data('bcless')=='darken'){
				bc_color = getColor(rgb2hex(bgcolor),'darken',persent);
			}
			else{
				bc_color = getColor(rgb2hex(bgcolor),'lighten',persent);
			}
			$(this).css('borderBottomColor',bc_color);
			$(this).css('borderTopColor',bc_color);
		    $(this).css('borderLeftColor',bc_color);
		    $(this).css('borderRightColor',bc_color);	    

		}
		else{
			setColor(this,'borderBottomColor',bgcolor);
		    setColor(this,'borderTopColor',bgcolor);
		    setColor(this,'borderLeftColor',bgcolor);
		    setColor(this,'borderRightColor',bgcolor);	    
		}
		

		
		
		if($(this).data('ct')=='fix'){
    		return ; // data-ct=fix固定颜色
    	}

    	var bgimg = $(this).css('backgroundImage');
    	//-webkit-linear-gradient(left, rgb(250, 235, 255), rgb(255, 255, 250), rgb(250, 235, 255))
    	if(bgimg.substring(0,24) == '-webkit-linear-gradient('){ //渐变色
    		var colors;
    		var type ;
    		if(bgimg.substring(0,30) == '-webkit-linear-gradient(left, '){
    			type = 'left';
    			colors = bgimg.substring(30 , (bgimg.length-1) );
    		}
    		else if(bgimg.substring(0,29) == '-webkit-linear-gradient(top, '){
    			type = 'top';
    			colors = bgimg.substring(29 , (bgimg.length-1) );
    		}
    		else if(bgimg.substring(0,31) == '-webkit-linear-gradient(right, '){
    			type = 'right';
    			colors = bgimg.substring(31 , (bgimg.length-1) );
    		}
    		else if(bgimg.substring(0,32) == '-webkit-linear-gradient(bottom, '){
    			type = 'bottom';
    			colors = bgimg.substring(32 , (bgimg.length-1) );
    		}

    		var color_arr = colors.split('),');
    		
    		var txt_color, gradient_color,main_color;
    		
    		if(isLightenColor(bgcolor)){
    			txt_color = getColor(rgb2hex(bgcolor),'darken','50%');
    			gradient_color = getColor(rgb2hex(bgcolor),'darken','10%');
    			main_color = getColor(rgb2hex(bgcolor),'lighten','1%');
    		}
    		else{
    			txt_color = getColor(rgb2hex(bgcolor),'lighten','50%');
    			gradient_color = getColor(rgb2hex(bgcolor),'lighten','20%');
    			main_color = getColor(rgb2hex(bgcolor),'lighten','5%');
    		}
    		
    		
    		if(color_arr.length ==3) {
				$(this).css('backgroundImage','-webkit-linear-gradient('+type+', '+main_color+', '+gradient_color+', '+main_color+')');
				$(this).css('color',txt_color);
    		}
    		else if(color_arr.length ==2) {
    			$(this).css('backgroundImage','-webkit-linear-gradient('+type+', '+main_color+', '+gradient_color+')');
				$(this).css('color',txt_color);
    		}
    		return;
    	}
		
    	var persent = $(this).data('clessp') ? $(this).data('clessp') : '50%';
    	
	    var bgC = $(this).css('backgroundColor');
	    if (bgC==='initial' || bgC === 'transparent' || bgC === "") {
	    	var fc = $(this).get(0).style.color; //$(this).css('color');
	    	if(fc && fc != "" && fc != 'inherit' && !isGreyColor(fc)) {
	    		var txt_color;
	    		if(isLightenColor(bgcolor)){
	    			txt_color = getColor(rgb2hex(bgcolor),'darken',persent);
	    			$(this).css('color',txt_color);
	    		}
	    		else{
	    			//if(fc && !isGreyColor(fc) ) {
			        	$(this).css('color',bgcolor);
		    		//}
	    		}
	    	}
	    } else {
	    	//var bgC_hex = rgb2hex(bgC);
	    	if(!isGreyColor(bgC)){	    		
	    		if($(this).data('bcless')){	    			
	    			var bgpersent = $(this).data('bclessp') ? $(this).data('bclessp') : '30%';	    			
					var bc_color = getColor(rgb2hex(bgcolor),$(this).data('bcless'),bgpersent);
					$(this).css('backgroundColor',bc_color);
				}
	    		else{
	    			$(this).css('backgroundColor',bgcolor);
	    		}	    		
	    		
	    		var txt_color;
	    		if(isLightenColor(bgcolor)){
	    			txt_color = getColor(rgb2hex(bgcolor),'darken',persent)
	    		}
	    		else{
	    			txt_color = getColor(rgb2hex(bgcolor),'lighten',persent);
	    		}
		        //if(color && !isGreyColor(color) ) {
		        $(this).css('color',txt_color);
		        //}
	    	}
	    	else{
	    		var fc = $(this).get(0).style.color; //$(this).css('color');
		    	if(fc && fc != "" && fc != 'inherit' && !isGreyColor(fc)) {
			        $(this).css('color',bgcolor);
		    	}
	    	}
	    }
	});
    		
	obj.find("*").each(function() {
		//fix inherit color;
		var fc = $(this).css('color');
		$(this).find('*').each(function() {
			var nfc = $(this).css('color');
			if(nfc == fc){ $(this).css('color','inherit') }
		});
	});
	var result = obj.html();
	obj=null;
	return result;
}

function setColor(obj,colorType,color){
	var c = $(obj).css(colorType);
    if (c === 'transparent') {
    	return;
    } else {
    	if(!isGreyColor(c)){
    		$(obj).css(colorType,color);
    	} 
    }
}

function rgb2hex(color){
 rgb = color.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
 return (rgb && rgb.length === 4) ? "#" +
  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : color;
}

function isLightenColor(color){
	var c = rgb2hex(color);
	var r = ("" + c.substring(1,3));
	var g = ("" + c.substring(3,5));
	var b = ("" + c.substring(5,7));
	
	// 80 ~ 128  C0 ~ 192
	if(r > 'C0' && g > 'C0' && b > 'C0' ){
		return true;
	}
	else{
		return false;
	}
}

function isGreyColor(color){
	var c = rgb2hex(color);
	var r = ""+c.substring(1,3);
	var g = ""+c.substring(3,5);
	var b = ""+c.substring(5,7);
	if(r==g && g==b ){ // && r>"dd"    || r>"dd" && g > "dd" && b > "dd"
		return true;
	}
	else{
		return false;
	}
}

//alert(rgb2hex('rgb(249, 110, 87)'));


function insertHtml(html){
	var oEditor = ckeditors['WxMsgContent'];
	// Check the active editing mode.
	if (oEditor.mode == 'wysiwyg' ){
		// Insert the desired HTML.
		if(current_select_bgcolor){
			 html = parseHtml(html,current_select_bgcolor,current_select_color);
		}
		oEditor.insertHtml(html);
	}
	else{
		alert($.jslanguage.wysiswyg_mode );
	}
}



function set_style(styles){
	//ckeditors['WxMsgContent'].focus();
	//ckeditors['WxMsgContent'].execCommand('selectAll');

	ckeditors['WxMsgContent'].execCommand('removeFormat');
	
	var element = ckeditors['WxMsgContent'].getSelection().getStartElement();
	
	if(element.getName() == 'img'){ //图片时直接应用到图片
		element.setStyles(styles);
	}
	else{
		// 应用到编辑器的单项
		var style = new CKEDITOR.style( { element: element.getName(), styles: styles} );
		ckeditors['WxMsgContent'].applyStyle( style );
	}
	

	//应用到全部内容，会修改后重置，撤销操作会失效
	/*var html = ckeditors['WxMsgContent'].getData();	
	var obj = $('<div id="editor-content">'+html+"</div>");
	obj.find(selector).each(function(){
		$(this).removeAttr('style');
		$(this).css(styles);
	});
	ckeditors['WxMsgContent'].setData(obj.html());*/

}
</script>

<!-- 
var masonryed = false;


onMixEnd: function(state){
					var $container = $('#editor-styles .editor-template-list');
					if(masonryed){
						$container.masonry( 'destroy' );  
					}					
				    $container.masonry({
				        itemSelector: '.col-xs-6:visible',
				        animate: true,       
				        animationOptions: {
				            duration: 400,
				            easing: 'linear',
				            queue: false
				        }
				    });
				    masonryed = true;
				}
'jquery/jquery.masonry.min.js', -->
{{$this->Html->script(array(				
	            'jquery/jquery.mixitup.min.js',    
	        ));
	}}
	
	<script>	
	$(function(){
		
	    $('.editor-template-list').mixItUp({
	    	layout:{display:'block'},
	    	callbacks:{}
	    });
	});
	
	</script>


<div class="modal fade" id="templateModal" tabindex="-1" role="dialog"  aria-hidden="true">
  <div class="modal-dialog"  style="width:900px;">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">{{__('Close')}}</span></button>
        <h4 class="modal-title">请选择要使用的模板</h4>
      </div>
      <div class="modal-body" id="template-modal-body">
        
      </div>
      <div class="modal-footer">
      	<label><input type="checkbox" id="load-template-modal" checked="checked">每次都自动弹出模板选择窗口</label>
        <button type="button" class="btn btn-default" data-dismiss="modal">{{__('Close')}}</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->




{{$this->Html->script(array( 'less-1.7.0.min.js',
				'ZeroClipboard/ZeroClipboard.min.js',));}}
<script>
var less_parser = new less.Parser;

function getColor(color,type,num){
	var str = '';
	less_parser.parse('*{color:'+type+'('+color+','+num+')}',	function (err, tree) {
		  str = tree.toCSS();
		  str = str.replace(/\n/g, '').replace(/ /g,'').replace('*{color:','').replace(';}','');
		  
	});
	return str;
}

ZeroClipboard.config( { swfPath: "{{$this->Html->url('/js/ZeroClipboard/ZeroClipboard.swf')}}" } );

function openTplModal(){
	$('#templateModal').modal('show');
	$('#template-modal-body').html('正在加载').load('{{$this->Html->url("/editor_styles/myTemplates")}} #my-templates',function(){
		//$('#my-templates .nav-tabs li:first').trigger('click');
		 $('#my-templates .nav-tabs a:first').tab('show')
	})
}


$(function(){
	
	$('#tab-tpl-trigger').click(function(){
		if($('#editor-tpls-list').html()==""){
			$('#editor-tpls-list').html('正在加载').load('{{$this->Html->url("/editor_styles/myTemplates?suffix=-1")}} #tpl-tab-content',function(){
				$('#editor-tpls-list').find('.col-md-3').removeClass('col-md-3').addClass('col-md-6');
				if( $('#favorite-tpl-list-1').find('.editor-style-content').size() ==0 ){
					$('#favorite-tpl-list-li').remove();
				}
				if( $('#personal-tpl-list-1').find('.editor-style-content').size() ==0 ){
					$('#personal-tpl-list-li').remove();
				}
				$('#editor-tpls-navtab a:first').tab('show');				
			})
		}		
	})
	
	$('#clear-editor').click(function(){
		if(confirm('是否确认清空内容，清空后内容将无法恢复')){
			ckeditors['WxMsgContent'].setData("");
		}		
	});
	
	$('#load-template-modal').click(function(){		
		if( window.localStorage){ // 是否打开选择模板的弹窗			
			if(this.checked){
				window.localStorage.loadTemplate = "true";
			}
			else{
				window.localStorage.loadTemplate = "false";
			}
		}
	})
	
	if(typeof localStorage.loadTemplate == "undefined" ||  window.localStorage && window.localStorage.loadTemplate == "true")
	{
		openTplModal();
	}
	else{
		$('#load-template-modal').attr('checked',false);
	}
	
	
	$(document).on('click','#tpl-tab-content .editor-style-content',function(){ //选中模板后设置编辑器的内容		
		ckeditors['WxMsgContent'].setData($(this).html());
	
		var id = parseInt($(this).data('id'));
		if(id > 0){
			$('#template_id').val( id );
			$('#auto_cover_tpl').removeClass('hidden');
		}
		else{
			$('#template_id').val('');
			$('#auto_cover_tpl').addClass('hidden');
		}
		
		$('#template_name').val($(this).data('name'));
		$('#dialog-template-name').val($(this).data('name'));
		$('#templateModal').modal('hide');
	});
	
	$(document).on('click','#tpl-tab-content .template-cover',function(){ //选中模板后设置编辑器的内容	
		var tid = $(this).data('id');
		var obj = $('#template-'+tid);
		
		ckeditors['WxMsgContent'].setData(obj.html());
		
		var id = parseInt(obj.data('id'));
		
		if(id > 0){
			$('#template_id').val(id);
			$('#auto_cover_tpl').removeClass('hidden');
		}
		else{
			$('#template_id').val('');
			$('#auto_cover_tpl').addClass('hidden');
		}
		
		$('#template_name').val(obj.data('name'));
		$('#dialog-template-name').val(obj.data('name'));
		$('#templateModal').modal('hide');
	});
	
	
	$('#save-as-template').click(function(){		
		saveTemplate(this.form);
	});
	
	$('#html-to-image').click(function(){
		this.form.action = '/downloads/htmlToImage';
		this.form.submit();
	});
	var client = new ZeroClipboard( $('#copy-editor-html') );
	client.on( 'ready', function(event) {
		client.on( 'copy', function(event) {
	  		event.clipboardData.setData('text/html', ckeditors['WxMsgContent'].getData());
	  		event.clipboardData.setData('text/plain', ckeditors['WxMsgContent'].getData());
	  		//event.clipboardData.setData('text/plain', ckeditors['WxMsgContent'].document.getBody().getText());
	  		showSuccessMessage("已成功复制到剪切板");

	  		// var obj = $('<div class="alert alert-success" role="alert">已成功复制到剪切板</div>').insertBefore('#copy-editor-html');
	  		// setTimeout(function(){obj.remove();},3000);
		});
	});

	// client.on( 'error', function(event) {
	// 	ZeroClipboard.destroy();
	// } );
});

function saveTemplate(form){
	if(ckeditors['WxMsgContent'].getData() == ""){
		showErrorMessage("请先输入模板内容");
		ckeditors['WxMsgContent'].focus();
		return false;
	}
	
	if(!sso.check_userlogin({"callback":saveTemplate,"callback_args":arguments}))
		return false;
	
	$('#myModal').modal('show');
	$('#dialog-save-template').unbind('click').click(function(){
		if($('#dialog-template-name').val() == ""){
			$('#dialog-template-name').focus();
		}
		else{
			$('#template_name').val($('#dialog-template-name').val());
			form.action = '/editor_styles/saveTemplate';
			ajaxSubmitForm(form,function(){
				$('#myModal').modal('hide');
			});
		}		
	});
}
</script>
</div>
